<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>应急管理</title>
  <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;700&display=swap" rel="stylesheet">
  <link rel="icon" type="image/ico" href="pc/ico.png">
  <style>
    :root {
      --primary-color: #3498db;
      --secondary-color: #2ecc71;
      --background-color: #ecf0f1;
      --text-color: #2c3e50;
      --card-width: 300px;
      --card-height: 450px; /* 固定卡片高度 */
      --button-bg-color: #3498db;
      --button-text-color: #fff;
      --button-hover-bg-color: #2980b9;
      --modal-bg-color: rgba(0, 0, 0, 0.6);
      --modal-content-bg-color: #fff;
      --input-border-color: #bdc3c7;
      --input-focus-border-color: #3498db;
      --submit-button-bg-color: #2ecc71;
      --submit-button-hover-bg-color: #27ae60;
      --error-color: #e74c3c;
      --shadow-color: rgba(0, 0, 0, 0.1);
      --transition-speed: 0.3s;
    }

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'Noto Sans SC', sans-serif;
      background-color: var(--background-color);
      color: var(--text-color);
      line-height: 1.6;
      overflow-x: hidden;
    }

    .container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 40px 20px;
    }

    header {
      text-align: center;
      margin-bottom: 50px;
      position: relative;
      padding: 20px;
      background: linear-gradient(135deg, #6dd5ed, #2193b0);
      border-radius: 15px;
      color: white;
      box-shadow: 0 4px 8px var(--shadow-color);
    }

    h1 {
      font-size: 3em;
      margin-bottom: 10px;
      text-shadow: 1px 1px 2px rgba(0,0,0,0.2);
    }

    /* 查看已选择导师按钮 */
    button#view-selected-btn {
      position: absolute;
      top: 20px;
      right: 20px;
      padding: 10px 20px;
      background-color: var(--secondary-color);
      color: #fff;
      border: none;
      border-radius: 25px;
      cursor: pointer;
      transition: background-color var(--transition-speed);
      box-shadow: 0 4px 6px var(--shadow-color);
      font-weight: bold;
    }

    button#view-selected-btn:hover {
      background-color: #27ae60;
    }

    .mentor-grid {
      display: flex;
      flex-wrap: wrap;
      gap: 30px;
      justify-content: center;
      padding: 20px 0;
    }

    .mentor-card {
      background-color: #fff;
      border-radius: 15px;
      box-shadow: 0 10px 20px var(--shadow-color);
      overflow: hidden;
      transition: transform var(--transition-speed), box-shadow var(--transition-speed);
      display: flex;
      flex-direction: column;
      width: var(--card-width);
      height: var(--card-height); /* 固定高度 */
      position: relative;
      background: linear-gradient(145deg, #ffffff, #f0f0f0);
    }

    .mentor-card:hover {
      transform: translateY(-10px);
      box-shadow: 0 15px 30px var(--shadow-color);
    }

    .mentor-image-container {
      position: relative;
      overflow: hidden;
      padding-top: 56.25%; /* 16:9 aspect ratio */
      width: 100%;
    }

    .mentor-image {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform var(--transition-speed);
    }

    .mentor-card:hover .mentor-image {
      transform: scale(1.1);
    }

    .mentor-info {
      padding: 20px;
      flex: 1;
      display: flex;
      flex-direction: column;
      position: relative;
    }

    .mentor-name {
      font-size: 1.5em;
      font-weight: bold;
      margin-bottom: 10px;
      color: var(--primary-color);
      text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
    }

    .mentor-bio {
      font-size: 0.95em;
      color: var(--text-color);
      margin-bottom: 10px;
      /* 固定简介区域高度，使用overflow隐藏多余文本 */
      height: 60px; /* 根据需要调整高度 */
      overflow: hidden;
      position: relative;
      word-break: break-word;
    }

    .mentor-contact {
      font-size: 0.9em;
      color: var(--secondary-color);
      margin-bottom: 15px;
      display: flex;
      align-items: center;
    }

    .mentor-contact::before {
      content: "📞";
      margin-right: 8px;
    }

    .mentor-fields {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-bottom: 15px;
    }

    .field {
      background-color: #e0e0e0;
      color: var(--text-color);
      padding: 5px 10px;
      border-radius: 20px;
      font-size: 0.8em;
      transition: background-color var(--transition-speed);
    }

    .field:hover {
      background-color: #d5d5d5;
    }

    /* 选择导师按钮 */
    .select-btn {
      padding: 10px 15px;
      background-color: var(--button-bg-color);
      color: var(--button-text-color);
      border: none;
      border-radius: 20px;
      cursor: pointer;
      transition: background-color var(--transition-speed), transform var(--transition-speed);
      align-self: center;
      margin-top: auto; /* 将按钮推到容器底部 */
      font-weight: bold;
      box-shadow: 0 4px 6px var(--shadow-color);
    }

    .select-btn:hover {
      background-color: var(--button-hover-bg-color);
      transform: scale(1.05);
    }

    /* 已选择导师按钮样式 */
    .selected {
      background-color: #95a5a6;
      cursor: default;
      box-shadow: none;
      transition: background-color var(--transition-speed);
    }

    /* “查看更多”按钮样式 */
    .read-more-btn {
      background: none;
      border: none;
      color: var(--primary-color);
      cursor: pointer;
      padding: 0;
      font-size: 0.9em;
      text-decoration: underline;
      margin-top: 5px;
      display: block; /* 让按钮独占一行 */
      transition: color var(--transition-speed);
    }

    .read-more-btn:hover {
      color: var(--button-hover-bg-color);
    }

    /* 加载中样式 */
    .loading {
      text-align: center;
      font-size: 1.2em;
      color: var(--primary-color);
      padding: 20px;
      animation: fadeIn 1s ease-in-out;
    }

    /* 错误信息样式 */
    .error {
      text-align: center;
      font-size: 1.2em;
      color: var(--error-color);
      padding: 20px;
      animation: fadeIn 1s ease-in-out;
    }

    /* 模态框样式 */
    .modal {
      display: none; /* 默认隐藏 */
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: var(--modal-bg-color);
      justify-content: center;
      align-items: center;
      padding: 20px;
      animation: fadeIn 0.5s ease;
    }

    .modal-content {
      background-color: var(--modal-content-bg-color);
      padding: 20px;
      border-radius: 10px;
      max-width: 600px;
      width: 100%;
      position: relative;
      max-height: 90vh;
      overflow-y: auto;
      box-shadow: 0 4px 8px var(--shadow-color);
      animation: slideDown 0.5s ease;
    }

    /* 关闭按钮 */
    .close-btn {
      position: absolute;
      top: 10px;
      right: 15px;
      font-size: 1.5em;
      font-weight: bold;
      color: #aaa;
      cursor: pointer;
      transition: color var(--transition-speed);
    }

    .close-btn:hover {
      color: #000;
    }

    /* 已选择导师列表 */
    .selected-mentors {
      display: grid;
      grid-template-columns: 1fr;
      gap: 20px;
    }

    .selected-card {
      background-color: #fff;
      border-radius: 10px;
      box-shadow: 0 5px 15px var(--shadow-color);
      overflow: hidden;
      transition: all var(--transition-speed) ease;
      padding: 15px;
      position: relative;
      animation: fadeInUp 0.5s ease;
    }

    .selected-card h3 {
      margin-bottom: 10px;
      color: var(--primary-color);
      text-align: center;
      font-size: 1.2em;
    }

    .selected-card p {
      margin-bottom: 5px;
      color: #555;
    }

    .remove-btn {
      position: absolute;
      top: 10px;
      right: 10px;
      background-color: rgba(231, 76, 60, 0.8);
      border: none;
      color: #fff;
      border-radius: 50%;
      width: 25px;
      height: 25px;
      cursor: pointer;
      font-weight: bold;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: background-color var(--transition-speed);
    }

    .remove-btn:hover {
      background-color: rgba(192, 57, 43, 0.8);
    }

    /* 输入表单样式 */
    .form-group {
      margin-bottom: 15px;
      display: flex;
      flex-direction: column;
    }

    .form-group label {
      margin-bottom: 5px;
      font-weight: bold;
      color: var(--primary-color);
    }

    .form-group input,
    .form-group textarea {
      padding: 10px;
      border: 1px solid var(--input-border-color);
      border-radius: 5px;
      font-size: 1em;
      transition: border-color var(--transition-speed);
    }

    .form-group input:focus,
    .form-group textarea:focus {
      border-color: var(--input-focus-border-color);
      outline: none;
      box-shadow: 0 0 5px var(--input-focus-border-color);
    }

    /* 提交按钮 */
    .submit-btn {
      padding: 10px 20px;
      background-color: var(--submit-button-bg-color);
      color: #fff;
      border: none;
      border-radius: 20px;
      cursor: pointer;
      transition: background-color var(--transition-speed), transform var(--transition-speed);
      font-size: 1em;
      display: block;
      margin: 0 auto;
      font-weight: bold;
      box-shadow: 0 4px 6px var(--shadow-color);
    }

    .submit-btn:hover {
      background-color: var(--submit-button-hover-bg-color);
      transform: scale(1.05);
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      .container {
        padding: 20px 10px;
      }

      header {
        padding: 15px;
      }

      h1 {
        font-size: 2.5em;
      }

      .mentor-grid {
        justify-content: center;
      }

      .mentor-card {
        width: 100%;
        max-width: var(--card-width);
        height: auto; /* 高度自适应 */
      }

      .mentor-image-container {
        padding-top: 80%; /* 调整图片比例 */
      }

      .mentor-info {
        padding: 15px;
      }

      .mentor-name {
        font-size: 1.3em;
      }

      .mentor-bio, .mentor-contact {
        font-size: 0.85em;
      }

      .field {
        font-size: 0.75em;
        padding: 4px 10px;
      }

      /* 调整查看已选择导师按钮 */
      button#view-selected-btn {
        padding: 8px 16px;
        font-size: 0.9em;
      }

      /* 调整卡片高度以适应内容 */
      .mentor-info {
        flex: none; /* 取消flex属性 */
      }
    }

    @media (max-width: 480px) {
      h1 {
        font-size: 2em;
      }

      .mentor-image-container {
        padding-top: 100%;
      }

      .mentor-name {
        font-size: 1.2em;
      }

      .mentor-bio, .mentor-contact {
        font-size: 0.8em;
      }

      .field {
        font-size: 0.7em;
        padding: 3px 8px;
      }

      /* 调整查看已选择导师按钮 */
      button#view-selected-btn {
        padding: 6px 12px;
        font-size: 0.8em;
      }

      /* 模态框内容 */
      .modal-content {
        padding: 15px;
      }

      .form-group label {
        font-size: 0.9em;
      }

      .form-group input,
      .form-group textarea {
        font-size: 0.9em;
      }

      .submit-btn {
        font-size: 0.9em;
        padding: 8px 16px;
      }
    }

    /* 动画效果 */
    @keyframes fadeIn {
      from { opacity: 0; }
      to { opacity: 1; }
    }

    @keyframes slideDown {
      from { transform: translateY(-20px); opacity: 0; }
      to { transform: translateY(0); opacity: 1; }
    }

    @keyframes fadeInUp {
      from { opacity: 0; transform: translateY(20px); }
      to { opacity: 1; transform: translateY(0); }
    }
  </style>
</head>
<body>
<div class="container">
  <header>
    <h1>导师选择</h1>
    <button id="view-selected-btn">查看已选择导师</button>
  </header>

  <main class="mentor-grid" id="mentor-grid">
    <!-- 导师卡片会在这里通过JS动态插入 -->
  </main>

  <!-- 加载中和错误信息 -->
  <div id="status-message"></div>
</div>

<!-- 模态框：查看已选择导师 -->
<div id="selected-modal" class="modal">
  <div class="modal-content">
    <span class="close-btn">&times;</span>
    <h2>已选择的导师</h2>
    <div class="selected-mentors" id="selected-mentors">
      <!-- 已选择导师卡片会在这里插入 -->
    </div>
    <div id="no-selected-message" class="error" style="display: none;">您尚未选择任何导师。</div>
  </div>
</div>

<!-- 模态框：选择导师时输入信息 -->
<div id="select-modal" class="modal">
  <div class="modal-content">
    <span class="close-btn">&times;</span>
    <h2>选择导师</h2>
    <form id="select-form">
      <div class="form-group">
        <label for="application-reason">申请理由</label>
        <textarea id="application-reason" name="applicationReason" rows="3" required></textarea>
      </div>
      <div class="form-group">
        <label for="research-interests">喜欢的研究方向</label>
        <textarea id="research-interests" name="researchInterests" rows="3" required></textarea>
      </div>
      <!-- 隐藏的导师ID字段 -->
      <input type="hidden" id="mentor-id" name="mentorId">
      <button type="submit" class="submit-btn">提交选择</button>
      <div id="form-error" class="error" style="display: none;"></div>
    </form>
  </div>
</div>

<!-- 模态框：导师详细信息 -->
<div id="mentor-detail-modal" class="modal">
  <div class="modal-content">
    <span class="close-btn">&times;</span>
    <div id="mentor-detail-content">
      <!-- 导师详细信息会在这里插入 -->
    </div>
  </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', () => {
    const mentorGrid = document.getElementById('mentor-grid');
    const statusMessage = document.getElementById('status-message');
    const viewSelectedBtn = document.getElementById('view-selected-btn');
    const selectedModal = document.getElementById('selected-modal');
    const selectModal = document.getElementById('select-modal');
    const mentorDetailModal = document.getElementById('mentor-detail-modal');
    const closeBtns = document.querySelectorAll('.close-btn');
    const selectedMentorsContainer = document.getElementById('selected-mentors');
    const noSelectedMessage = document.getElementById('no-selected-message');
    const selectForm = document.getElementById('select-form');
    const formError = document.getElementById('form-error');
    const mentorIdInput = document.getElementById('mentor-id');
    const mentorDetailContent = document.getElementById('mentor-detail-content');

    // 存储已选择的导师ID集合
    let selectedMentorIds = new Set();

    // 显示加载中信息
    statusMessage.textContent = '正在加载导师信息...';
    statusMessage.classList.add('loading');
    checkLoginStatus();
    // 检查用户登录状态
    async function checkLoginStatus() {
      try {
        const response = await fetch('/api/v1/users/getUserInfo', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        const result = await response.json();
        if (result.code !== 200 || !result.data.username) {
          // 如果未登录，则跳转到登录页面
          window.location.href = '/login.html';
        }
      } catch (error) {
        console.error("登录检测失败", error);
        window.location.href = '/login.html'; // 出错时也跳转到登录页面
      }
    }

    // 异步获取导师数据和已选择导师数据
    Promise.all([
      fetch('/api/v1/mentorProfiles/getMentorProfile'),
      fetch('/api/v1/applications/getByUserId', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include' // 如果后端使用Cookie进行身份验证
      })
    ])
            .then(async ([mentorsResponse, selectedResponse]) => {
              if (!mentorsResponse.ok) {
                throw new Error(`获取导师信息失败: ${mentorsResponse.status}`);
              }
              if (!selectedResponse.ok) {
                throw new Error(`获取已选择导师信息失败: ${selectedResponse.status}`);
              }

              const mentorsData = await mentorsResponse.json();
              const selectedData = await selectedResponse.json();

              // 清除加载中信息
              statusMessage.textContent = '';
              statusMessage.classList.remove('loading');

              // 判断API返回结构
              if (mentorsData.code !== undefined && mentorsData.code !== 200) {
                throw new Error(`API返回错误: ${mentorsData.message}`);
              }

              if (selectedData.code !== undefined && selectedData.code !== 200) {
                throw new Error(`API返回错误: ${selectedData.message}`);
              }

              const mentors = mentorsData.code === undefined ? mentorsData : mentorsData.data;
              const selectedMentors = selectedData.code === undefined ? selectedData : selectedData.data;

              // 填充已选择导师ID集合
              selectedMentorIds = new Set(selectedMentors.map(app => app.mentorId));

              if (!mentors || mentors.length === 0) {
                statusMessage.textContent = '暂无导师信息。';
                statusMessage.classList.add('error');
                return;
              }

              mentors.forEach(mentor => {
                // 创建导师卡片
                const mentorCard = document.createElement('article');
                mentorCard.classList.add('mentor-card');

                // 创建导师图片容器
                const mentorImageContainer = document.createElement('div');
                mentorImageContainer.classList.add('mentor-image-container');

                // 创建导师头像图片元素
                const mentorImage = document.createElement('img');
                mentorImage.classList.add('mentor-image');
                mentorImage.src = `/api/v1/mentorProfiles/profilePicture/${encodeURIComponent(mentor.profilePicture)}`;
                mentorImage.alt = mentor.mentorName;
                mentorImage.loading = 'lazy';

                // // 图片加载失败时使用默认图片
                // mentorImage.onerror = () => {
                //   mentorImage.src = 'https://via.placeholder.com/300x250?text=无图片';
                // };

                // 将图片添加到图片容器中
                mentorImageContainer.appendChild(mentorImage);

                // 创建导师信息容器
                const mentorInfo = document.createElement('div');
                mentorInfo.classList.add('mentor-info');
                mentorInfo.dataset.mentorId = mentor.mentorId; // 添加 data-mentor-id 属性

                // 创建导师姓名元素
                const mentorName = document.createElement('h2');
                mentorName.classList.add('mentor-name');
                mentorName.textContent = mentor.mentorName;

                // 创建导师简介元素
                const mentorBio = document.createElement('p');
                mentorBio.classList.add('mentor-bio');
                mentorBio.textContent = mentor.bio;

                // 创建“查看更多”按钮，始终显示
                const readMoreBtn = document.createElement('button');
                readMoreBtn.classList.add('read-more-btn');
                readMoreBtn.textContent = '查看更多';
                readMoreBtn.addEventListener('click', () => {
                  openMentorDetailModal(mentor.mentorId);
                });

                // 添加到导师简介容器
                mentorInfo.appendChild(mentorName);
                mentorInfo.appendChild(mentorBio);
                mentorInfo.appendChild(readMoreBtn); // 始终添加“查看更多”按钮

                // 创建导师联系方式元素
                const mentorContact = document.createElement('p');
                mentorContact.classList.add('mentor-contact');
                mentorContact.textContent = `联系方式：${mentor.contactInfo}`;

                // 创建导师领域（研究方向）元素
                const mentorFields = document.createElement('div');
                mentorFields.classList.add('mentor-fields');

                // 将研究领域按中文逗号分割并创建元素
                const fields = mentor.researchFields.split('，');
                fields.forEach(field => {
                  const fieldElement = document.createElement('span');
                  fieldElement.classList.add('field');
                  fieldElement.textContent = field.trim();
                  mentorFields.appendChild(fieldElement);
                });

                // 创建选择导师按钮
                const selectBtn = document.createElement('button');
                selectBtn.classList.add('select-btn');
                selectBtn.textContent = '选择导师';

                // 检查该导师是否已被选择
                if (selectedMentorIds.has(mentor.mentorId)) {
                  selectBtn.textContent = '已选择';
                  selectBtn.classList.add('selected');
                  selectBtn.disabled = true;
                }

                // 添加点击事件处理器
                selectBtn.addEventListener('click', () => {
                  openSelectModal(mentor, selectBtn);
                });

                // 将所有元素添加到导师信息容器中
                mentorInfo.appendChild(mentorContact);
                mentorInfo.appendChild(mentorFields);
                mentorInfo.appendChild(selectBtn);

                // 将图片容器和信息容器添加到导师卡片中
                mentorCard.appendChild(mentorImageContainer);
                mentorCard.appendChild(mentorInfo);

                // 将导师卡片添加到导师卡片容器中
                mentorGrid.appendChild(mentorCard);
              });
            })
            .catch(error => {
              console.error('获取导师信息时出错:', error);
              statusMessage.textContent = `加载失败: ${error.message}`;
              statusMessage.classList.add('error');
            });

    // 查看已选择导师按钮点击事件
    viewSelectedBtn.addEventListener('click', () => {
      openSelectedModal();
    });

    // 关闭所有模态框
    closeBtns.forEach(btn => {
      btn.addEventListener('click', () => {
        btn.closest('.modal').style.display = 'none';
        formError.style.display = 'none';
        mentorDetailContent.innerHTML = ''; // 清空导师详情内容
      });
    });

    // 点击模态框外部关闭
    window.addEventListener('click', (event) => {
      if (event.target === selectedModal) {
        selectedModal.style.display = 'none';
      }
      if (event.target === selectModal) {
        selectModal.style.display = 'none';
        formError.style.display = 'none';
      }
      if (event.target === mentorDetailModal) {
        mentorDetailModal.style.display = 'none';
        mentorDetailContent.innerHTML = ''; // 清空导师详情内容
      }
    });

    // 选择导师时打开选择模态框
    function openSelectModal(mentor, selectBtn) {
      selectModal.style.display = 'flex';

      // 填充隐藏的导师ID
      mentorIdInput.value = mentor.mentorId;

      // 重置并显示表单
      selectForm.reset();
      formError.style.display = 'none';

      // 设置表单提交事件
      selectForm.onsubmit = function(event) {
        event.preventDefault();
        formError.style.display = 'none';

        const applicationReason = document.getElementById('application-reason').value.trim();
        const researchInterests = document.getElementById('research-interests').value.trim();
        const mentorId = document.getElementById('mentor-id').value;

        // 简单验证
        if (!applicationReason || !researchInterests) {
          formError.textContent = '请填写所有必填项。';
          formError.style.display = 'block';
          return;
        }

        // 构建提交数据
        const payload = {
          mentorId: parseInt(mentorId),
          applicationReason: applicationReason,
          researchInterests: researchInterests
        };
        // 发送选择导师请求
        fetch('/api/v1/applications/submit', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(payload)
        })
                .then(response => {
                  if (!response.ok) {
                    throw new Error(`选择失败`);
                  }
                  return response.json();
                })
                .then(data => {
                  // 判断API返回结构
                  if (data.code !== undefined && data.code !== 200) {
                    throw new Error(`选择失败: ${data.message}`);
                  }

                  // 显示成功提示（可选）
                  alert('导师选择成功！');

                  // 更新按钮状态
                  selectBtn.textContent = '已选择';
                  selectBtn.classList.add('selected');
                  selectBtn.disabled = true;

                  // 关闭选择模态框
                  selectModal.style.display = 'none';

                  // 更新所有按钮状态
                  updateSelectButtons();
                })
                .catch(error => {
                  console.error('选择导师时出错:', error);
                  formError.textContent = `提交失败: ${error.message}`;
                  formError.style.display = 'block';
                });
      };
    }

    // 打开已选择导师模态框
    function openSelectedModal() {
      // 显示加载中信息
      selectedMentorsContainer.innerHTML = '';
      noSelectedMessage.style.display = 'none';
      const loadingMessage = document.createElement('div');
      loadingMessage.classList.add('loading');
      loadingMessage.textContent = '正在加载已选择的导师...';
      selectedMentorsContainer.appendChild(loadingMessage);

      // 调用后端API获取已选择的导师
      fetch('/api/v1/applications/getByUserId', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include' // 如果后端使用Cookie进行身份验证
      })
              .then(response => {
                if (!response.ok) {
                  throw new Error(`网络响应不是OK: ${response.status}`);
                }
                return response.json();
              })
              .then(data => {
                // 清除加载中信息
                selectedMentorsContainer.innerHTML = '';

                // 判断API返回结构
                if (data.code !== undefined && data.code !== 200) {
                  throw new Error(`API返回错误: ${data.message}`);
                }

                const applications = data.code === undefined ? data : data.data;

                if (!applications || applications.length === 0) {
                  noSelectedMessage.style.display = 'block';
                  return;
                }

                applications.forEach(application => {
                  // 创建已选择导师卡片
                  const selectedCard = document.createElement('div');
                  selectedCard.classList.add('selected-card');

                  // 导师姓名
                  const selectedName = document.createElement('h3');
                  selectedName.textContent = application.mentorName;
                  selectedName.style.color = 'var(--primary-color)';
                  selectedName.style.fontSize = '1.2em';
                  selectedName.style.textAlign = 'center';
                  selectedCard.appendChild(selectedName);

                  // 理由
                  const reasonPara = document.createElement('p');
                  reasonPara.innerHTML = `<strong>理由：</strong> ${application.applicationReason}`;
                  selectedCard.appendChild(reasonPara);

                  // 喜欢的研究方向
                  const interestsPara = document.createElement('p');
                  interestsPara.innerHTML = `<strong>喜欢的研究方向：</strong> ${application.researchInterests}`;
                  selectedCard.appendChild(interestsPara);

                  // 状态
                  const statusPara = document.createElement('p');
                  statusPara.innerHTML = `<strong>状态：</strong> ${application.status === 'pending' ? '待处理' : application.status === 'approved' ? '已批准' : '已拒绝'}`;
                  statusPara.style.color = application.status === 'pending' ? 'orange' :
                          (application.status === 'approved' ? 'green' : 'red');
                  statusPara.style.marginTop = '5px';
                  statusPara.style.textAlign = 'center';
                  statusPara.style.fontWeight = 'bold';
                  selectedCard.appendChild(statusPara);

                  // 创建一个隐藏的申请ID字段，用于删除操作
                  const applicationId = application.applicationId;

                  // 移除按钮
                  const removeBtn = document.createElement('button');
                  removeBtn.classList.add('remove-btn');
                  removeBtn.textContent = '×';
                  removeBtn.title = '移除导师';

                  removeBtn.addEventListener('click', () => {
                    // 移除导师的逻辑
                    if (!confirm(`确定要移除导师 ${application.mentorName} 吗？`)) return;

                    fetch(`/api/v1/applications/delete/${applicationId}`, {
                      method: 'DELETE',
                      headers: {
                        'Content-Type': 'application/json'
                      },
                      credentials: 'include' // 如果后端使用Cookie进行身份验证
                    })
                            .then(response => {
                              if (!response.ok) {
                                throw new Error(`网络响应不是OK: ${response.status}`);
                              }
                              return response.json();
                            })
                            .then(deleteData => {
                              // 判断API返回结构
                              if (deleteData.code !== undefined && deleteData.code !== 200) {
                                throw new Error(`API返回错误: ${deleteData.message}`);
                              }

                              // 移除成功后，重新打开模态框以刷新列表
                              alert('导师已移除！');
                              selectedModal.style.display = 'none';
                              openSelectedModal();
                            })
                            .catch(error => {
                              console.error('移除导师时出错:', error);
                              alert(`移除失败: ${error.message}`);
                            });
                  });

                  selectedCard.appendChild(removeBtn);

                  // 添加到已选择导师容器中
                  selectedMentorsContainer.appendChild(selectedCard);
                });
              })
              .catch(error => {
                console.error('获取已选择导师时出错:', error);
                selectedMentorsContainer.innerHTML = '';
                const errorMessage = document.createElement('div');
                errorMessage.classList.add('error');
                errorMessage.textContent = `加载失败: ${error.message}`;
                selectedMentorsContainer.appendChild(errorMessage);
              });

      // 打开模态框
      selectedModal.style.display = 'flex';
    }

    // 打开导师详细信息模态框
    function openMentorDetailModal(mentorId) {
      mentorDetailModal.style.display = 'flex';
      mentorDetailContent.innerHTML = '<div class="loading">正在加载导师详细信息...</div>';
      console.log('调用API获取导师详细信息，导师ID:', mentorId);

      // 调用后端API获取导师详细信息
      fetch(`/api/v1/mentorProfiles/getMentorProfileById/${mentorId}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include' // 如果后端使用Cookie进行身份验证
      })
              .then(response => {
                if (!response.ok) {
                  throw new Error(`网络响应不是OK: ${response.status}`);
                }
                return response.json();
              })
              .then(data => {
                mentorDetailContent.innerHTML = ''; // 清空加载中信息
                console.log('导师详细信息获取成功:', data);

                // 判断API返回结构
                const mentor = data.code === undefined ? data : data.data;

                // 创建导师详细信息元素
                const detailName = document.createElement('h3');
                detailName.textContent = mentor.mentorName;
                detailName.style.color = 'var(--primary-color)';
                detailName.style.textAlign = 'center';
                detailName.style.marginBottom = '15px';
                detailName.style.fontSize = '1.5em';

                const detailBio = document.createElement('p');
                detailBio.innerHTML = `<strong>简介：</strong> ${mentor.bio}`;
                detailBio.style.marginBottom = '10px';
                detailBio.style.wordBreak = 'break-word'; // 允许在单词内换行

                const detailContact = document.createElement('p');
                detailContact.innerHTML = `<strong>联系方式：</strong> ${mentor.contactInfo}`;
                detailContact.style.marginBottom = '10px';

                const detailFields = document.createElement('p');
                detailFields.innerHTML = `<strong>研究方向：</strong> ${mentor.researchFields}`;
                detailFields.style.marginBottom = '10px';

                const detailCreatedAt = document.createElement('p');
                detailCreatedAt.innerHTML = `<strong>创建时间：</strong> ${new Date(mentor.createdAt).toLocaleString()}`;
                detailCreatedAt.style.marginBottom = '10px';

                // 将所有详细信息添加到模态框内容中
                mentorDetailContent.appendChild(detailName);
                mentorDetailContent.appendChild(detailBio);
                mentorDetailContent.appendChild(detailContact);
                mentorDetailContent.appendChild(detailFields);
                mentorDetailContent.appendChild(detailCreatedAt);
              })
              .catch(error => {
                console.error('获取导师详细信息时出错:', error);
                mentorDetailContent.innerHTML = `<div class="error">加载失败: ${error.message}</div>`;
              });
    }

    // 更新“选择导师”按钮状态（用于移除后重新启用按钮）
    function updateSelectButtons() {
      fetch('/api/v1/applications/getByUserId', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include' // 如果后端使用Cookie进行身份验证
      })
              .then(response => {
                if (!response.ok) {
                  throw new Error(`网络响应不是OK: ${response.status}`);
                }
                return response.json();
              })
              .then(data => {
                // 判断API返回结构
                if (data.code !== undefined && data.code !== 200) {
                  throw new Error(`API返回错误: ${data.message}`);
                }

                const applications = data.code === undefined ? data : data.data;
                const selectedMentorIdsUpdated = new Set(applications.map(app => app.mentorId));

                const selectButtons = document.querySelectorAll('.select-btn');
                selectButtons.forEach(btn => {
                  const mentorInfo = btn.closest('.mentor-info');
                  const mentorId = parseInt(mentorInfo.dataset.mentorId);

                  if (selectedMentorIdsUpdated.has(mentorId)) {
                    btn.textContent = '已选择';
                    btn.classList.add('selected');
                    btn.disabled = true;
                  } else {
                    btn.textContent = '选择导师';
                    btn.classList.remove('selected');
                    btn.disabled = false;
                  }
                });
              })
              .catch(error => {
                console.error('更新按钮状态时出错:', error);
              });
    }
  });
</script>
</body>
</html>
